"""
CSV数据处理器
"""
import csv
import ast
import numpy as np
import asyncio
from datetime import datetime


async def run(socketio, app, record=False, **kwargs):
    """ 主处理循环 """
    csv_file = kwargs.get('csv_path', 'data.csv')

    while True:
        try:
            with open(csv_file, 'r') as f:
                reader = csv.DictReader(f)
                for row in reader:
                    if not app.config['IS_STREAMING']:
                        await asyncio.sleep(1)
                        continue

                    # 数据处理
                    points = np.array(ast.literal_eval(row['positions']))
                    app.config['MESSAGE_COUNT'] += 1

                    # 发送到前端
                    socketio.emit('lidar_data', {
                        'points': points.tolist(),
                        'timestamp': datetime.now().isoformat(),
                        'frame_id': app.config['MESSAGE_COUNT']
                    })

                    await asyncio.sleep(0.1)  # 控制播放速度

        except Exception as e:
            print(f"CSV处理错误: {str(e)}")
            await asyncio.sleep(1)